//
//  ChatSysInfoDao.m
//  SportSocial
//
//  Created by yull on 15/1/28.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "ChatSysInfoDao.h"

@implementation ChatSysInfoDao

+ (instancetype)shareInstance
{
    static ChatSysInfoDao *infoDao = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        infoDao = [[ChatSysInfoDao alloc] init];
    });
    return infoDao;
}

- (void)createTable
{
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        NSMutableArray *sqlArray = [NSMutableArray arrayWithObjects:
                                    @"CREATE TABLE IF NOT EXISTS chatSysInfo ("
                                    "[id] integer NOT NULL PRIMARY KEY AUTOINCREMENT, "
                                    "[userId] integer,"
                                    "[userName] varchar,"
                                    "[groupId] integer,"
                                    "[groupName] varchar,"
                                    "[createId] integer,"
                                    "[createName] varchar,"
                                    "[msgId] integer,"
                                    "[icon] varchar,"
                                    "[content] varchar,"
                                    "[time] double,"
                                    "[isRead] bool,"
                                    "[key] varchar,"
                                    "[friendType] integer ,"
                                    "[groupType] integer ,"
                                    "[infoType] integer)"
                                    ,nil];
        
        [db beginTransaction];
        BOOL result = YES;
        for (NSString *sql in sqlArray) {
            result &= [db executeUpdate:sql];
        }
        if (result) {
            result &= [db commit];
        }
        
        if (!result) {
            [db rollback];
        }
    }];
}

- (BOOL)addOrUpdateChatInfo:(ChatSystemInfo *)chatInfo
{
    BOOL isExist = [self checkIsExist:chatInfo];
    if (isExist) {
        return [self updateChatInfo:chatInfo];
    }else {
        return [self insertChatInfo:chatInfo];
    }
}

- (BOOL)checkIsExist:(ChatSystemInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = nil;
        resultSet = [db executeQuery:@"select * from chatSysInfo where msgId=?",[NSNumber numberWithLongLong:chatInfo.msgId]];
        if (resultSet.next) {
            result = YES;
            chatInfo.dbId = [resultSet longForColumn:@"id"];
        }
        [resultSet close];
    }];
    return result;
}

- (BOOL)updateChatInfo:(ChatSystemInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update chatSysInfo set userId=?,userName=?,groupId=?,groupName=?,createId=?,createName=?,msgId=?,icon=?,content=?,time=?,groupType=?,friendType=?,infoType=?,key=? where id=?",
                  [NSNumber numberWithLongLong:chatInfo.userId],
                  chatInfo.userName,
                  [NSNumber numberWithLongLong:chatInfo.groupId],
                  chatInfo.groupName,
                  [NSNumber numberWithLongLong:chatInfo.createId],
                  chatInfo.createName,
                  [NSNumber numberWithLongLong:chatInfo.msgId],
                  chatInfo.icon,
                  chatInfo.content,
                  [NSNumber numberWithDouble:chatInfo.time],
                  [NSNumber numberWithInteger:chatInfo.groupType],
                  [NSNumber numberWithInteger:chatInfo.friendType],
                  [NSNumber numberWithInteger:chatInfo.infoType],
                  chatInfo.key,
                  [NSNumber numberWithLongLong:chatInfo.dbId]];
    }];
    return result;
}

- (BOOL)insertChatInfo:(ChatSystemInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"insert into chatSysInfo (userId,userName,groupId,groupName,createId,createName,msgId,icon,content,time,groupType,friendType,infoType,key,isRead) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  [NSNumber numberWithLongLong:chatInfo.userId],
                  chatInfo.userName,
                  [NSNumber numberWithLongLong:chatInfo.groupId],
                  chatInfo.groupName,
                  [NSNumber numberWithLongLong:chatInfo.createId],
                  chatInfo.createName,
                  [NSNumber numberWithLongLong:chatInfo.msgId],
                  chatInfo.icon,
                  chatInfo.content,
                  [NSNumber numberWithDouble:chatInfo.time],
                  [NSNumber numberWithInteger:chatInfo.groupType],
                  [NSNumber numberWithInteger:chatInfo.friendType],
                  [NSNumber numberWithInteger:chatInfo.infoType],
                  chatInfo.key,
                  [NSNumber numberWithBool:chatInfo.isRead]];
        if (result) {
            chatInfo.dbId = db.lastInsertRowId;
        }
    }];
    return result;
}

- (NSMutableArray *)selectAlChatInfo
{
    __block NSMutableArray *returnArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from chatSysInfo"];
        while (resultSet.next) {
            [returnArray addObject:[ChatSystemInfo systemInfoWithResultSet:resultSet]];
        }
        [resultSet close];
    }];
    return returnArray;
}

#pragma mark - public
- (BOOL)addChatInfoArray:(NSArray *)array
{
    BOOL result = YES;
    for (ChatSystemInfo *chatInfo in array) {
        result &= [self addOrUpdateChatInfo:chatInfo];
    }
    return result;
}

- (ChatInfo *)getTotalSystemInfo
{
    __block ChatInfo *chatInfo = [[ChatInfo alloc] init];
    chatInfo.name = @"系统消息";
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *rs = [db executeQuery:@"select * from chatSysInfo order by id desc limit(1)"];
        if (rs.next) {
            chatInfo.time = [rs longLongIntForColumn:@"time"];
        }
        [rs close];
        
        if (chatInfo.time > 0) {
            rs = [db executeQuery:@"select count(*) from chatSysInfo where isRead=1"];
            NSInteger unreadCount = [rs intForColumnIndex:0];
            chatInfo.unReadCount = unreadCount;
            [rs close];
            
            rs = [db executeQuery:@"select count(*) from chatSysInfo"];
            
            if (rs.next) {
                NSInteger count = [rs intForColumnIndex:0];
                chatInfo.content = [[NSString alloc] initWithFormat:@"您有%d条系统消息",count];
            }
            [rs close];
        }
    }];
    
    if (chatInfo.time > 0) {
        return chatInfo;
    }
    return nil;
}

- (BOOL)clearUnRead
{
    __block BOOL ret = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        ret = [db executeUpdate:@"update chatSysInfo set isRead=0"];
    }];
    return ret;
}

- (BOOL)deleteSystemInfo:(ChatSystemInfo *)sysInfo
{
    __block BOOL ret = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        ret = [db executeUpdate:@"delete from chatSysInfo where id=?",[NSNumber numberWithLongLong:sysInfo.dbId]];
    }];
    return ret;
}

- (BOOL)clearSystemInfo
{
    __block BOOL ret = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        ret = [db executeUpdate:@"delete from chatSysInfo"];
    }];
    return ret;
}
@end
